package com.book.breakage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.book.breakage.entity.Accident;
import com.book.breakage.service.AccidentService;
import com.book.business.entity.BookSell;
import com.book.business.service.BookSellService;
import com.book.common.utils.WareBook;
import com.book.shelves.entity.BookStore;
import com.book.shelves.service.BookStoreService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.FebsUtil;
import com.book.stat.entity.BreakageStat;
import com.book.stat.service.BreakageStatService;
import com.book.warehouse.entity.WarehouseBook;
import com.book.warehouse.service.WarehouseBookService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: 张高赫
 * @Description: 20173954
 */

@Controller
public class AccidentController extends BaseController {
    @Autowired
    AccidentService accidentService;
    @Autowired
    BreakageStatService breakageStatService;
    @Autowired
    BookStoreService bookStoreService;
    @Autowired
    WarehouseBookService warehouseBookService;
    @Autowired
    BookSellService bookSellService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/accident")
    public String breReturnIndex() {
        return FebsUtil.view("breakage/accident/accidentList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/accident/add")
    public String accidentAdd() {
        return FebsUtil.view("breakage/accident/accidentAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/accident/update/{id}")
    public String accidentUpdate(@PathVariable Integer id, ModelMap modelMap) {
        Accident accident = accidentService.getById(id);
        modelMap.addAttribute("accident", accident);
        return FebsUtil.view("breakage/accident/accidentUpdate");
    }

    @GetMapping("accident")
    @ResponseBody
    @RequiresPermissions("accident:view")
    public FebsResponse findAccident(Accident accident) {
        return new FebsResponse().success().data(accidentService.accidentList(accident));
    }

    @Log("访问意外报损")
    @GetMapping("accident/list")
    @ResponseBody
    @RequiresPermissions("accident:view")
    public FebsResponse accidentList(QueryRequest request, Accident accident) {
        Map<String, Object> dataTable = getDataTable(this.accidentService.accidentPage(request, accident));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("意外报损-新增")
    @PostMapping("accident")
    @ResponseBody
    @RequiresPermissions("accident:add")
    @ControllerEndpoint(operation = "报损新增", exceptionMessage = "新增报损信息失败")
    public FebsResponse accidentAdd(@Valid Accident accident) {
        WarehouseBook warehouseBook = warehouseBookService.getOne(new QueryWrapper<WarehouseBook>().lambda()
                .eq(WarehouseBook::getBookname, accident.getBookname())
                .eq(WarehouseBook::getPutaway, "1"));
        if (warehouseBook == null) {
            return new FebsResponse().message("抱歉仓库没有该书籍。");
        }
        WareBook.wareBookChange(warehouseBook.getBookname(), "减少", accident.getNumber());
        accident.setStatus("3")
                .setBooktype(warehouseBook.getType())
                .setBookmoney(warehouseBook.getBookmoney())
                .setPubid(warehouseBook.getPurchasefactory())
                .setUsername(getCurrentUser().getUsername())
                .setTotalmoney(warehouseBook.getBookmoney() * accident.getNumber())
                .setDamagedate(new Date());
        this.accidentService.accidentAdd(accident);
        return new FebsResponse().success();
    }

    @Log("意外报损-修改")
    @PostMapping("accident/update")
    @ResponseBody
    @RequiresPermissions("accident:update")
    @ControllerEndpoint(operation = "修改报损信息成功", exceptionMessage = "修改报损信息失败")
    public FebsResponse accidentUpdate(Accident accident) {
        Accident byId = accidentService.getById(accident.getId());
        if ("3".equals(byId.getStatus())) {
            return new FebsResponse().message("管理员手动添加报损，不能操作！");
        }
        this.accidentService.accidentUpdate(accident);
        return new FebsResponse().success();
    }

    @Log("意外报损-删除")
    @PostMapping("accident/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("accident:delete")
    @ControllerEndpoint(operation = "删除报损成功", exceptionMessage = "删除报损信息失败")
    public FebsResponse accidentDelete(@PathVariable String ids) {
        String[] arr = ids.split(",");
        List<Accident> accidentList = accidentService.accidentApply(arr);
        for (int i = 0; i < accidentList.size(); i++) {
            if ("0".equals(accidentList.get(i).getStatus())) {
                return new FebsResponse().message("报损申请还未进行审批，不能删除！");
            }
            if ("3".equals(accidentList.get(i).getStatus())) {
                return new FebsResponse().message("管理员手动添加报损，不能操作！");
            }
            this.accidentService.accidentDelete(arr);
        }
        return new FebsResponse().success();
    }

    @Log("意外报损-审批")
    @PostMapping("accident/apply/{ids}")
    @ResponseBody
    @RequiresPermissions("accident:apply")
    @ControllerEndpoint(operation = "审批意外报损成功", exceptionMessage = "审批意外报损失败")
    public FebsResponse accidentApply(@PathVariable String ids) {
        String[] arr = ids.split(",");
        List<Accident> accidentList = accidentService.accidentApply(arr);
        for (int i = 0; i < accidentList.size(); i++) {
            if ("1".equals(accidentList.get(i).getStatus())) {
                return new FebsResponse().message("该条报损信息已经审批，请勿重复审批！");
            }
            if ("2".equals(accidentList.get(i).getStatus())) {
                return new FebsResponse().message("该报损信息已经驳回，不能再进行审批！");
            }
            if ("3".equals(accidentList.get(i).getStatus())) {
                return new FebsResponse().message("管理员手动添加报损，不能操作！");
            }
            accidentList.get(i).setStatus("1");
            accidentService.accidentUpdate(accidentList.get(i));
            breakageStatService.update(new UpdateWrapper<BreakageStat>().lambda()
                    .eq(BreakageStat::getBreakageid, accidentList.get(i).getBreakageid())
                    .set(true, BreakageStat::getOmit, "1"));
            BookStore bookStore = bookStoreService.getOne(new QueryWrapper<BookStore>().lambda()
                    .eq(BookStore::getBookname, accidentList.get(i).getBookname())
                    .eq(BookStore::getFlag, "1"));
            if (bookStore.getNum() == accidentList.get(i).getNumber()) {
                bookStoreService.removeById(bookStore.getId());
            } else {
                bookStore.setNum(bookStore.getNum() - accidentList.get(i).getNumber());
                bookStoreService.updateBookStore(bookStore);
            }
        }
        return new FebsResponse().success();
    }

    @Log("意外报损-驳回")
    @PostMapping("accident/no/{id}")
    @ResponseBody
    @RequiresPermissions("accident:no")
    @ControllerEndpoint(operation = "成功驳回", exceptionMessage = "驳回失败")
    public FebsResponse accidentNo(@PathVariable String id) {
        Accident accident = accidentService.getById(id);
        if ("1".equals(accident.getStatus())) {
            return new FebsResponse().message("该条报损申请，已通过，不能进行驳回！");
        }
        if ("2".equals(accident.getStatus())) {
            return new FebsResponse().message("该条报损申请，已被驳回，请勿重复操作！");
        }
        if ("3".equals(accident.getStatus())) {
            return new FebsResponse().message("管理员手动添加报损，不能操作！");
        }
        accident.setStatus("2");
        accidentService.accidentUpdate(accident);
        BreakageStat breakageStat = breakageStatService.getOne(new QueryWrapper<BreakageStat>().lambda().eq(BreakageStat::getBreakageid, accident.getBreakageid()));
        if (breakageStat != null) {
            breakageStatService.removeById(breakageStat.getId());
        }
        WareBook.wareBookChange(accident.getBookname(), "增加", accident.getNumber());
        WarehouseBook warehouseBookServiceOne = warehouseBookService.getOne(new QueryWrapper<WarehouseBook>().lambda()
                .eq(WarehouseBook::getBookname, accident.getBookname()).eq(WarehouseBook::getPutaway, "1"));
        if (warehouseBookServiceOne == null) {
            bookStoreService.remove(new QueryWrapper<BookStore>().lambda()
                    .eq(BookStore::getBookname, accident.getBookname()).notIn(BookStore::getFlag, "1"));
            bookSellService.remove(new QueryWrapper<BookSell>().lambda().eq(BookSell::getBookname, accident.getBookname()));
        }
        BookStore bookStore = bookStoreService.getOne(new QueryWrapper<BookStore>().lambda()
                .eq(BookStore::getBookname, accident.getBookname())
                .eq(BookStore::getFlag, "1"));
        if (bookStore.getNum() == accident.getNumber()) {
            bookStoreService.removeById(bookStore.getId());
        } else {
            bookStore.setNum(bookStore.getNum() - accident.getNumber());
            bookStoreService.updateBookStore(bookStore);
        }
        return new FebsResponse().success();
    }
}
